//
//  ALLogManager.m
//  ios-loan-assistant
//
//  Created by hcs on 2018/9/7.
//  Copyright © 2018年 guoqingping. All rights reserved.
//

#import "ALLogManager.h"
@interface ALLogManager ()
@property (nonatomic, assign) LogLevel level;

@end
@implementation ALLogManager
{
    dispatch_queue_t _queue;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _queue = dispatch_queue_create("jiguang.loan.log", NULL);
        [self setLevel:LogLevelInfo];
    }
    return self;
}

+ (instancetype)share {
    static ALLogManager * instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[ALLogManager alloc] init];
    });
    return instance;
}

+ (void)setLogLevel:(LogLevel)level {
    dispatch_async([ALLogManager share]->_queue, ^{
        [[ALLogManager share] setLogLevel:level];
    });
}

+ (void)logFlag:(LogFlag)flag
           file:(const char *)file
         format:(NSString *)format, ... {
    
    va_list args;
    va_start(args, format);
    NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
    va_end(args);
    
    dispatch_async([ALLogManager share]->_queue, ^{
        [[ALLogManager share] logFlag:flag file:file message:message];
    });
    
}

- (void)logFlag:(LogFlag)flag
           file:(const char *)file
        message:(NSString *)message {
    if (!(flag & self.level)) {
        return;
    }
    NSString * fileName = [[NSString stringWithFormat:@"%s", file] lastPathComponent];
    NSUInteger dotLocation = [fileName rangeOfString:@"." options:NSBackwardsSearch].location;
    if (dotLocation != NSNotFound)
    {
        fileName = [fileName substringToIndex:dotLocation];
    }
    NSLog(@" | [%@] - [%@] %@", [self flagInitial:flag], fileName, message);
}

- (void)setLogLevel:(LogLevel)level {
    self.level = level;
}

- (NSString *)flagInitial:(LogFlag)flag {
    switch (flag) {
        case LogFlagInfo:
            return @"I";
            break;
        case LogFlagDebug:
            return @"D";
            break;
        case LogFlagWarning:
            return @"W";
            break;
        case LogFlagError:
            return @"E";
            break;
        case LogFlagVerbose:
            return @"V";
            break;
    }
    return @"Unknown";
}

@end
